package com.lingnan.wanxiangxinxun.controller.admin;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.lingnan.wanxiangxinxun.entity.dto.EmployeeDTO;
import com.lingnan.wanxiangxinxun.entity.po.Authority;
import com.lingnan.wanxiangxinxun.entity.po.Employee;
import com.lingnan.wanxiangxinxun.entity.vo.common.PageVO;
import com.lingnan.wanxiangxinxun.entity.vo.common.Result;
import com.lingnan.wanxiangxinxun.entity.vo.service.AuthorityVO;
import com.lingnan.wanxiangxinxun.service.IEmployeeService;
import com.lingnan.wanxiangxinxun.util.jwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author swl
 * @since 2025-03-13
 */
@RestController
@RequestMapping("/admin/employee")
public class EmployeeController {

    private static final Logger log = LoggerFactory.getLogger(EmployeeController.class);
    @Autowired
    private IEmployeeService employeeService;


    //新增员工
    @PostMapping("/add")
    public Result addEmployee(@RequestBody EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employee.setCreateTime(LocalDateTime.now());
        try {
            employeeService.save(employee);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("新增失败");
        }
        return Result.success();
    }


    //删除员工
    @DeleteMapping("/delete/{ids}")
    public Result deleteEmployee(@PathVariable List<Integer> ids) {
        try {
            employeeService.removeBatchByIds(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
        return Result.success();
    }


    //员工信息修改
    @PutMapping("/update")
    public Result updateEmployee(@RequestBody EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        try {
            employeeService.updateById(employee);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("修改失败");
        }
        return Result.success();
    }

    //修改某个职位的权限
    @PostMapping("/updateAuthority")
    public Result updateAuthority(@RequestParam Integer positionId, @RequestBody List<Integer> authorityIds) {
        employeeService.updateAuthority(positionId, authorityIds);
        return Result.success();
    }


    //查找员工--分页查所有
    @GetMapping("/getAllInPage")
    public Result getEmployeeInPage(@RequestParam(defaultValue = "1") long current,
                              @RequestParam(defaultValue = "10") long size) {
        PageVO<Employee> allInPage = employeeService.getAllInPage(current, size);
        return Result.success(allInPage);
    }


    //查找员工--根据条件查
    @PostMapping("/getAllInCondition")
    public Result getEmployeeInCondition(@RequestBody EmployeeDTO employeeDTO) {
        PageVO<Employee> allInCondition = employeeService.getInCondition(employeeDTO);
        return Result.success(allInCondition);
    }


    //查找--根据id查询
    @GetMapping("/getById")
    public Result getEmployeeById(@RequestParam List<Integer> ids) {
        List<Employee> employeeList = employeeService.getEmployeeListByIds(ids);
        return Result.success(employeeList);
    }


    //查找--员工登录
    @PostMapping("/signIn")
    public Result empLogin(@RequestParam Integer id, @RequestParam String password) throws JsonProcessingException {
        Employee employee = employeeService.empSignIn(id, password);
        if (employee == null) {
            return Result.error("账号或密码错误");
        }
        if (!employee.getStatus()) {
            return Result.error("该账户已被禁用");
        }
        employee.setPassword("******");

        //返回jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", employee.getId());
        claims.put("name" ,employee.getName());
        claims.put("position" ,employee.getPosition());

        String EmployeeLoginJwt = jwtUtils.GenerateJwt(claims); //生成令牌,令牌中包含了该员工的部分信息
        return Result.success(EmployeeLoginJwt); //向前端返回令牌
    }


    //查找--查找员工职位对应的权限（用于返回路由）
    @GetMapping("/getEmpAuthority/{id}")
    public Result getEmpAuthority(@PathVariable Integer id) {
        List<AuthorityVO> authorityVO = employeeService.getAuthority(id);
        return Result.success(authorityVO);
    }

    //查找--所有的权限
    @GetMapping("/getAllAuthority")
    public Result getAllAuthority() {
        List<Authority> authorityList = employeeService.getAllAuthority();
        return Result.success(authorityList);
    }

    //查找--查找员工职位对应的权限（用于修改权限）
    @GetMapping("/getPositionAuthority/{positionId}")
    public Result getPositionAuthority(@PathVariable Integer positionId) {
        List<Authority> authorityList = employeeService.getPositionAuthority(positionId);
        return Result.success(authorityList);
    }

}
